<?php

/*
  [GRIRMS] (C) 2009 Grandison & JM Technologies

  @author kevin<hasson.lai@mobile-grandison.com>
  @version $Id: global.func.php v1 2009-09-16 kevin $
 */

if (!defined('IN_GRIRMS')) {
    exit('Access Denied');
}

function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
    global $authkey;
    $ckey_length = 4;
    $key = md5($key ? $key : $authkey);
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';

    $cryptkey = $keya . md5($keya . $keyc);
    $key_length = strlen($cryptkey);

    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
    $string_length = strlen($string);

    $result = '';
    $box = range(0, 255);

    $rndkey = array();
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }

    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }

    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }

    if ($operation == 'DECODE') {
        if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        return $keyc . str_replace('=', '', base64_encode($result));
    }
}

function clearcookies() {
    global $_userid, $_userpwd, $_username;
    foreach (array('auth','username','usertype') as $k) {
        dsetcookie($k);
    }
    $_userid = 0;
    $_userpwd = $_username = '';
}

function daddslashes($string, $force = 0) {
    !defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
    if (!MAGIC_QUOTES_GPC || $force) {
        if (is_array($string)) {
            foreach ($string as $key => $val) {
                $string[$key] = daddslashes($val, $force);
            }
        } else {
            $string = addslashes($string);
        }
    }
    return $string;
}

function dhtmlspecialchars($string) {
    if (is_array($string)) {
        foreach ($string as $key => $val) {
            $string[$key] = dhtmlspecialchars($val);
        }
    } else {
        $string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1',
                        //$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
                        str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
    }
    return $string;
}

function dsetcookie($var, $value = '', $life = 0, $prefix = 1, $httponly = false) {
    global $cookiepre, $cookiedomain, $cookiepath, $timestamp, $_SERVER;
    $var = ($prefix ? $cookiepre : '') . $var;
    if ($value == '' || $life < 0) {
        $value = '';
        $life = -1;
    }
    $life = $life > 0 ? $timestamp + $life : ($life < 0 ? $timestamp - 31536000 : 0);
    $path = $httponly && PHP_VERSION < '5.2.0' ? "$cookiepath; HttpOnly" : $cookiepath;
    $secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
    if (PHP_VERSION < '5.2.0') {
        setcookie($var, $value, $life, $path, $cookiedomain, $secure);
    } else {
        setcookie($var, $value, $life, $path, $cookiedomain, $secure, $httponly);
    }
}

function strexists($haystack, $needle) {
    return!(strpos($haystack, $needle) === FALSE);
}

function checkPermission($m, $p) {
    return;
    global $_userid, $userdata, $_user_type;
    $referer = urlencode($_SERVER["REQUEST_URI"]);
    if ($m == 'admin' && $_userid == 0 && $p != 'login') {
        header("location:/" . APP_URL . "/index.php/admin/login/referer/{$referer}");
        exit();
    }
    return;
    $page = "{$m}_{$p}";
    $has_permission = true;
    switch ($page) {
        case 'region_index':
            $has_permission = $_user_type == 1 ? true : false;
            break;
        case 'region_index':
            $has_permission = $_user_type == 2 ? true : false;
            break;
        case 'inform_index':
            $has_permission = $_user_type == 3 ? true : false;
            break;
        case 'inform_index':
            $has_permission = $_user_type == 4 ? true : false;
            break;
        default:
            $has_premission = false;
    }
    if (!$has_permission) {
        showmessage("您没有权限访问该页面！");
        exit();
    }
}

function get_perpage($new_cpp, $perpage = 10, $id = '') {
    global $db, $_userid, $userdata, $this_script, $_DCOOKIE;
    $cpp = 0;
    $id = $id == '' ? $this_script : $id;
    $new_cpp = intval($new_cpp);

    if (isset($_DCOOKIE["cpp_$id"])) {
        $cpp = $_DCOOKIE["cpp_$id"];
    }
    if ($cpp > 0) {
        $perpage = intval($cpp);
    }
    if ($new_cpp > 0) {
        if ($new_cpp != $cpp) {
            dsetcookie("cpp_$id", $new_cpp, 86400 * 30);
        }
        $perpage = $new_cpp;
    }
    return $perpage;
}

/* AJAX 分页 */

function get_ajax_page($line_nums, $js_function_name, $lines_per_page, $curr_page) {
    $lines_per_page_arr[] = 5;
    $lines_per_page_arr[] = 10;
    $lines_per_page_arr[] = 20;
    $lines_per_page_arr[] = 50;
    $lines_per_page_arr[] = 100;
    $lines_per_page_arr[] = 1000;
    if (strlen($lines_per_page) > 0)
        $lines_per_page = $lines_per_page;
    $total_pages = ceil($line_nums / $lines_per_page);
    if (strlen(trim($curr_page)) == 0 || substr($curr_page, 0, 1) == '0')
        $curr_page = 1;
    elseif ($curr_page > $total_pages)
        $curr_page = $total_pages;
    $sel_str = "<select name=\"lines_per_page\" id=\"lines_per_page\" onchange=\"" . $js_function_name . "('1');\">";
    foreach ($lines_per_page_arr as $value) {
        if ($value == $lines_per_page)
            $sel_str.="<option value=\"" . $value . "\" selected>" . $value . "</option>";
        else
            $sel_str.="<option value=\"" . $value . "\">" . $value . "</option>";
    }
    $sel_str.="</select>";
    $out_page_str = "";
    $out_page_str .= "<div align='center'>总共<b>" . $line_nums . "</b>条数据，" . $sel_str . "条数据/页，共<b>" . $total_pages . "</b>页";
    $first_page_str = "&nbsp;<a href='###' onclick=\"javascript:" . $js_function_name . "(1);\">首页</a>";
    $pre_page_str = "&nbsp;<a href='###' onclick=\"javascript:" . $js_function_name . "(" . ($curr_page - 1) . ");\">上页</a>";
    if ($curr_page == 1) {
        $first_page_str = "&nbsp;首页";
        $pre_page_str = "&nbsp;上页";
    }
    $out_page_str .= $first_page_str . $pre_page_str;
    $med_page_nums = 5;
    $pre_page_str = $next_page_str = "";
    for ($i = 1; $i <= $med_page_nums; $i++) {
        if (($curr_page - $i) > 0)
            $pre_page_str = "&nbsp;<a href='###' onclick=\"javascript:" . $js_function_name . "(" . ($curr_page - $i) . ");\">" . ($curr_page - $i) . "</a>" . $pre_page_str;
        if (($curr_page + $i) <= $total_pages)
            $next_page_str.="&nbsp;<a href='###' onclick=\"javascript:" . $js_function_name . "(" . ($curr_page + $i) . ");\">" . ($curr_page + $i) . "</a>";
    }
    $out_page_str .= $pre_page_str . "&nbsp;<b><font color='red'>" . $curr_page . "</font></b>" . $next_page_str;
    $next_page_str = "&nbsp;<a href='###' onclick=\"javascript:" . $js_function_name . "(" . ($curr_page + 1) . ");\">下页</a>";
    $last_page_str = "&nbsp;<a href='###' onclick=\"javascript:" . $js_function_name . "(" . $total_pages . ");\">尾页</a>";
    if ($curr_page == $total_pages) {
        $next_page_str = "&nbsp;下页";
        $last_page_str = "&nbsp;尾页";
    }
    $out_page_str .= $next_page_str . $last_page_str;
    $out_page_str .= "&nbsp;第<input type='text' name='search_page_num' id='search_page_num_id' size='2' value='{$curr_page}' onkeyup=\"javascript:value=value.replace(/[^\d]/g,'');\" onbeforepaste=\"clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))\" />页";
    $out_page_str .= "&nbsp;<input type='button' name='page_btn' value='前往' id='page_btn_id' onclick=\"javascript:" . $js_function_name . "(document.getElementById('search_page_num_id').value);\" />";
    $out_page_str .= "</div>";
    return $out_page_str;
}

//pagecute
function multi($num, $perpage, $curpage, $param, $maxpages = 0, $page = 10, $autogoto = TRUE, $simple = FALSE) {
    global $m, $p;
    $lang['prev'] = '<<';
    $lang['next'] = '>>';

    if ($num > $perpage) {
        $multipage = '';
        $ajaxtarget = !empty($_GET['ajaxtarget']) ? " ajaxtarget=\"" . dhtmlspecialchars($_GET['ajaxtarget']) . "\" " : '';

        $mpurl = 'index.php?m=' . $m . '&p=' . $p . $param . '&';
        $realpages = 1;
        $offset = 2;

        $realpages = @ceil($num / $perpage);
        $pages = $maxpages && $maxpages < $realpages ? $maxpages : $realpages;

        if ($page > $pages) {
            $from = 1;
            $to = $pages;
        } else {
            $from = $curpage - $offset;
            $to = $from + $page - 1;
            if ($from < 1) {
                $to = $curpage + 1 - $from;
                $from = 1;
                if ($to - $from < $page) {
                    $to = $page;
                }
            } elseif ($to > $pages) {
                $from = $pages - $page + 1;
                $to = $pages;
            }
        }

        for ($i = $from; $i <= $to; $i++) {
            if ($i == $curpage) {
                $class = ' class="current"';
                $link = $i;
            } else {
                $class = '';
                $link = '<a href="' . $mpurl . 'page=' . $i . ($ajaxtarget && $i == $pages && $autogoto ? '#' : '') . '"' . $ajaxtarget . '>' . $i . '</a>';
            }
            $multipage .= '<span' . $class . '>' . $link . '</span>';
        }
        if (!$simple) {
            if ($curpage > 1) {
                $class = '';
                $link = '<a href="' . $mpurl . 'page=' . ($curpage - 1) . '" class="prev"' . $ajaxtarget . '>' . $lang['prev'] . '</a>';
            } else {
                $class = ' class="disabled"';
                $link = $lang['prev'];
            }
            $first_link = '<span' . $class . '>' . $link . '</span>'
                    . ($curpage - $offset > 1 && $pages > $page ? '<a href="' . $mpurl . 'page=1" class="first"' . $ajaxtarget . '>1</a>' . ($from > 2 ? ' … ' : '') : '');

            if ($curpage < $pages) {
                $class = '';
                $link = '<a href="' . $mpurl . 'page=' . ($curpage + 1) . '" class="next"' . $ajaxtarget . '>' . $lang['next'] . '</a>';
            } else {
                $class = ' class="disabled"';
                $link = $lang['next'];
            }
            $last_link = ( $to < $pages ? ($to < $realpages - 1 ? '…' : '') . '<a href="' . $mpurl . 'page=' . $pages . '" class="last"' . $ajaxtarget . '>' . $realpages . '</a>' : '') . '<span' . $class . '>' . $link . '</span>';

            $multipage = $first_link . $multipage . $last_link;
        }
    } else {
        $multipage = '<span class="disabled">' . $lang['prev'] . '</span><span class="current">1</span><span class="disabled">' . $lang['next'] . '</span>';
    }

    return $multipage;
}

//生成静态页面
//$m 模块 $p 页面
//$parameter 参数 如：array('article_id'=>'11')
//$parameter_name 用作文件名的参数名 如 设$parameter_name为article_id时，生成的文件名为11.html
//$with_date 是否按日期生成文件夹
function php2html($m, $p, $parameter = array(), $parameter_name = '', $with_date = false, $date_format = 'Ym') {
    if($m == '' || $p == '') return false;
    global $db,$cookiepre,$category_list, $category_tree, $system_settings;
    foreach ($parameter as $k => $v) {
        $$k = $v;
    }

    require APP_ROOT . "module/{$m}/{$p}.php";

    if (empty($parameter_name)) {
        $dir = "/data/html/{$m}/";
        $file_name = $p . '.html';
    } else {
        $dir = "/data/html/{$m}/{$p}/" . ($with_date ? date($date_format) . '/' : '' );
        $file_name = $$parameter_name . '.html';
    }
    
    if (is_dir(APP_ROOT.$dir) || mkdir(APP_ROOT.$dir, 0755, true)) {
        ob_start();
        include template("{$m}/html/{$p}.html", 'module');
        $html_content = ob_get_contents();
        ob_end_clean();
        return file_put_contents(APP_ROOT.$dir . $file_name, $html_content) > 0 ? addslashes($dir . $file_name) : false;
    } else {
        return false;
    }
}

//template
function template($file, $_tpldir='') {
    global $tplrefresh;
    $tpldir = $_tpldir == '' ? $GLOBALS['tpldir'] : $_tpldir;
    $tplfile = APP_ROOT . "./$tpldir/$file";
    $objfile = APP_CACHEDIR . "./$tpldir/$file.tpl.php";
    checktplrefresh($file, $file, @filemtime($objfile), $tpldir);

    return $objfile;
}

function checktplrefresh($maintpl, $subtpl, $timecompare, $tpldir) {
    global $tplrefresh;
    if (empty($timecompare) || $tplrefresh == 1 || ($tplrefresh > 1 && !($GLOBALS['timestamp'] % $tplrefresh))) {
        $subtpl = APP_ROOT . $tpldir . '/' . $subtpl;
        if (empty($timecompare) || @filemtime($subtpl) > $timecompare) {
            require_once APP_ROOT . './include/template.func.php';
            parse_template($maintpl, $tpldir);
            return TRUE;
        }
    }
    return FALSE;
}

//PHP的unescape函数
function unescape($str, $charcode = "utf8") {
    $text = preg_replace_callback("/%u[0-9A-Za-z]{4}/", toUtf8, $str);
    return mb_convert_encoding($text, $charcode, 'utf-8');
}

/*  将系统配置写入缓存 */

function make_setting_cache($setting = array()) {
    global $db;
    cache_write('settings.php', empty($setting) ? $db->fetch_first("SELECT * FROM system_settings ORDER BY id DESC LIMIT 0,1") : $setting);
}

/*  获取系统配置 */

function get_settings() {
    if (!file_exists(APP_CACHEDIR . './data/settings.php')) {
        make_setting_cache();
    }
    return cache_read('settings');
}

/* 返回AJAX请求 */

function ajax_return($status, $info = '', $data = array()) {
    return array2json(array(
        'status' => intval($status),
        'info' => trim($info),
        'data' => $data
    ));
}

/* 将数组格式化为JSON */

function array2json($arr, $with_head=false) {
    if ($with_head)
        header("Content-Type: text/json");
    if (function_exists('json_encode'))
        return json_encode($arr); //Lastest versions of PHP already has this functionality.
 $parts = array();
    $is_list = false;

    //Find out if the given array is a numerical array
    $keys = array_keys($arr);
    $max_length = count($arr) - 1;
    if (($keys[0] == 0) and ($keys[$max_length] == $max_length)) {//See if the first key is 0 and last key is length - 1
        $is_list = true;
        for ($i = 0; $i < count($keys); $i++) { //See if each key correspondes to its position
            if ($i != $keys[$i]) { //A key fails at position check.
                $is_list = false; //It is an associative array.
                break;
            }
        }
    }

    foreach ($arr as $key => $value) {
        if (is_array($value)) { //Custom handling for arrays
            if ($is_list)
                $parts[] = array2json($value); /* :RECURSION: */
            else
                $parts[] = '"' . $key . '":' . array2json($value); /* :RECURSION: */
        } else {
            $str = '';
            if (!$is_list)
                $str = '"' . $key . '":';

            //Custom handling for multiple data types
            if (is_numeric($value))
                $str .= $value; //Numbers
 elseif ($value === false)
                $str .= 'false'; //The booleans
 elseif ($value === true)
                $str .= 'true';
            else
                $str .= '"' . addslashes($value) . '"'; //All other things
                // :TODO: Is there any more datatype we should be in the lookout for? (Object?)

            $parts[] = $str;
        }
    }
    $json = implode(',', $parts);

    if ($is_list)
        return '[' . $json . ']'; //Return numerical JSON
 return '{' . $json . '}'; //Return associative JSON
}

/* 将数组格式化为XML字符串 */

function array2xml($array, $level=0, $with_head=false) {
    if ($with_head)
        header("Content-Type: text/xml");
    $return = '';
    if ($level == 0) {
        $return = '<?xml version="1.0" encoding="utf-8" ?><root>';
    }
    foreach ($array as $key => $item) {
        if (!is_array($item)) {
            $return .= "<item key='{$key}'>{$item}</item>";
        } else {
            $return .= "<item key='{$key}'>";
            $return .= array2xml($item, $level + 1);
            $return .= "</item>";
        }
    }
    if ($level == 0) {
        $return .= '</root>';
    }
    return $return;
}

/* 将被array2xml格式化的XML还原 */

function xml2array($xml) {
    $return_array = array();
    foreach ($xml->childNodes as $node) {
        $length = $node->childNodes->length;
        $key = $node->getAttribute('key');
        if ($length == 1 and $node->firstChild->nodeType == XML_TEXT_NODE or empty($node->nodeValue)) {
            $return_array[$key] = $node->nodeValue;
        } else {
            $return_array[$key] = xml2array($node);
        }
    }
    return $return_array;
}

function showmessage($message, $url = null) {
    global $_userid, $_user_type, $userdata, $m, $p;
    include template("message.html");
    exit();
}

//获取根分类ID
function get_module_root_category_id($cat_id) {
    global $category_list, $category_tree;
    return $category_list[$cat_id]['parent_id'] > 1 ? get_module_root_category_id($category_list[$cat_id]['parent_id']) : $cat_id;
}
//获取各级分类ID，自上而下，以英文逗号分割
function get_cat_ids($id){
    global $category_list;
    if($category_list[$id]['parent_id'] > 1){
        return get_cat_ids($category_list[$id]['parent_id']).','.$id;
    }else{
        return $id;
    }
}
//获取OPTION数据，返回数组格式为 array(key=>value)
function get_option_array($type){
    global $db;
    return cache_exists('option_'.$type) ? cache_read('option_'.$type) : $db->fetch_all('SELECT `id`,`value` FROM `system_option` WHERE `type`=\'BRAND\'','id','value');
}

function update_cron() {
    global $db;
    $cron_file = APP_ROOT . 'crontab/L1Cron.task';
    $cron_content = '';
    $query = $db->query("SELECT * FROM task WHERE enabled=1");
    while ($row = $db->fetch_array($query)) {
        $minute = '';
        $hour = '';
        $day = '*';
        $month = '*';
        $week = '*';
        $id = $row['id'];
        $week = $row['weekdays'];
        $increase = 1;
        switch ($row['interval']) {
            case '1':
                $minute = "*";
                break;
            case '2':
                $minute = "0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58";
                break;
            case '3':
                $minute = "0,3,6,9,12,15,18,21,24,17,30,33,36,39,42,45,48,51,54,57";
                break;
            case '4':
                $minute = "0,4,8,12,16,20,24,28,32,36,40,44,48,52,56";
                break;
            case '5':
                $minute = "0,5,10,15,20,25,30,35,40,45,50,55";
                break;
            case '6':
                $minute = "0,6,12,18,24,30,36,42,48,54";
                break;
            case '10':
                $minute = "0,10,20,30,40,50";
                break;
            case '20':
                $minute = "0,20,40";
                break;
            case '30':
                $minute = "0,30";
                break;
            case '60':
                $minute = "0";
                break;
            default:
                $minute = "0";
                $increase = ceil($row['interval'] / 60);
                break;
        }

        for ($i = $row['start_time']; $i <= $row['stop_time']; $i+=$increase) {
            $hour .= ( $hour == '' ? '' : ',') . $i;
        }

        if ($cron_content != "")
            $cron_content .= "\n";
        $cron_content .= "$minute\t$hour\t$day\t$month\t$week\twget http://sd.gree.grirms.com/task_exec.php?id=$id";
    }
    file_put_contents($cron_file, $cron_content);
}

//从地理坐标系（经纬度）转换到北京54坐标系
function convertJWDToBeijing(&$jd, &$wd) {
    //其中x,y为上经纬坐标,由用户自己输入;
    //m,n分别代表全国54坐标
    if (!defined('PI'))
        define('PI', 3.14159265358);

    $m = 0.00;
    $n = 0.00;

    $g = 0.00669342162297;
    $x0 = 3458144.04;
    $y0 = -146121.96;
    $h = 1.000140682;
    $f = 0.013930556;
    $ll = 0.00;
    $X = 0.00;
    $t = 0.00;
    $N = 0.00;
    $a = 6378245.00;
    $W = 0.00;
    $p = 206265;
    $z = 0.00;
    $l = 0.00;
    $b = 6356863.01877;
    $c = 6399689.90178;
    $k = 0.00;

    $x = $wd;
    $y = $jd;
    $DH = 41.0;

    $L = 123.0; //(DH - 0.5) * 3.;

    $ll = $x * PI / 180;
    $k = $x * 3600;
    $l = ($y - $L) * PI / 180;
    $z = sqrt((0.00673852541468)) * cos($ll);
    $W = sqrt(1 - $g * pow(sin($ll), 2));
    $N = $a / $W;
    $t = tan($ll);

    $mm1 = (pow(cos($ll), 2) * (5 - pow($t, 2) + 9 * pow($z, 2) + 4 * pow($z, 4)) * pow($l, 2)) / 24;
    $mm2 = (pow(cos($ll), 4) * (61 - 58 * pow($t, 2) + pow($t, 4)) * pow($l, 4)) / 720;
    //克拉索夫斯基椭球的子午线弧长公式;
    $X = 111134.861 * $x - (32005.7799 * sin($ll) + 133.9238 * pow(sin($ll), 3) + 0.6973 * pow(sin($ll), 5) + 0.0039 * pow(sin($ll), 7)) * cos($ll);
    $m = $X + pow(cos($ll), 2) * $t * $N * pow($l, 2) * (0.5 + $mm1 + $mm2);

    $n = cos($ll) * $N * $l * (1 + (pow(cos($ll), 2) * (1 - pow($t, 2) + pow($z, 2)) * pow($l, 2)) / 6
            + (pow(cos($ll), 4) * (5 - 18 * pow($t, 2) + pow($t, 4) + 14 * pow($z, 2) - 58 * pow($z, 2) * pow($t, 2)) * pow($l, 5)) / 120);

    $jd = $m;
    $wd = $n + 21000000 + 500000;
}

?>
